package com.example.userservice.service;

import com.example.service.UserService;
import com.example.userservice.dao.TokenDao;
import com.example.userservice.dao.UserDao;
import com.example.userservice.pojo.Token;
import com.example.userservice.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author zhouyp
 * @program example-parent
 * @description
 * @create 2020-07-27
 */
@Service
@org.apache.dubbo.config.annotation.Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private TokenDao tokenDao;

	@Override
	public boolean isRegistered(String email) {
		final Integer count = userDao.countByEmail(email);
		if (count == null) return true;
		return count > 0;
	}

	@Override
	public boolean register(String email, String password) {
		final HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

		User user = new User();
		user.setEmail(email);
		user.setPassword(password);
		userDao.save(user);

		setToken(response, email);

		return true;
	}

	@Override
	public boolean login(String email, String password) {
		final HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		final Integer count = userDao.countByEmailAndPassword(email, password);
		if (count == null || count == 0) return false;
		setToken(response, email);
		return true;
	}

	private void setToken(HttpServletResponse response, String email) {
		String uuid = UUID.randomUUID().toString();
		Token token = new Token();
		token.setEmail(email);
		token.setToken(uuid);
		tokenDao.save(token);

		/*Cookie cookie = new Cookie("example-token", uuid);
		cookie.setPath("/");
		response.addCookie(cookie);*/
		response.addHeader("example-token", uuid);
	}
}
